package com.code.leetcode.idea;

import java.util.ArrayList;
import java.util.List;

/**
 * 超出时间限制。测试用例通过了，但耗时太长。
 * Time Limit Exceeded
 */
public class LeetCodeIdea006 {
    public static void main(String[] args) {
        LeetCodeIdea006 leetCodeIdea006 = new LeetCodeIdea006();
        String s = "PAYPALISHIRING";
        int numRows = 3;
        String result = leetCodeIdea006.convert(s, numRows);
        System.out.println(result.equals("PAHNAPLSIIGYIR"));
    }

    public String convert(String s, int numRows) {
        if (numRows < 2) {
            return s;
        }
        List<StringBuilder> rows = new ArrayList<>(numRows);
        for (int i = 0; i < numRows; i++) {
            rows.add(new StringBuilder());
        }
        int i = 0;
        int flag = 1;
        for (char cc : s.toCharArray()) {
            rows.get(i).append(cc);
            if (i == 0) {
                flag = 1;
            } else if (i == numRows - 1) {
                flag = -1;
            }
            if (flag == 1) {
                i++;
            }else {
                i--;
            }
        }
        StringBuilder result = new StringBuilder();
        rows.forEach(sb -> result.append(sb));
        return result.toString();
    }
}
